package com.zhangsl.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.zhangsl.service.UserService;
import com.zhangsl.vo.UserVO;

public class LoginInterceptor implements HandlerInterceptor {
	private final Log log = LogFactory.getLog(this.getClass());
	@Autowired
	private UserService userService;

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HttpSession session = request.getSession();

		UserVO user = (UserVO) session.getAttribute("user");
		UserVO userDB = null;
		if (null != user) {
			userDB = userService.findUserByName(user.getName());
			if (null != userDB && (user.getLastLoginTime().equals(userDB.getLastLoginTime()))) {
				session.removeAttribute("user");
				request.getContextPath();
				response.sendRedirect("/"); 
				return true;
			}
		}
		return false;

	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		log.info("********postHandle  HandlerInterceptor***********************");
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		log.info("********afterCompletion  HandlerInterceptor***********************");
	}

}